<template>
  <div class="login">
    <div class="loginName">登录</div>
    <van-form @submit="onSubmit">
      <van-field v-model="mobile"
                 name="用户名"
                 left-icon='user-o'
                 placeholder="请输入手机号"
                 :rules="[{ pattern: /^1[3456789]\d{9}$/, message: '输入手机号不能为空' }]" />
      <van-field v-model="code"
                 left-icon='user-o'
                 center
                 clearable
                 placeholder="请输入短信验证码"
                 :rules="[{ pattern: /^\d{6}$/, message: '请输入6位的验证码' }]">
        <template #button>
          <van-count-down v-if="remaining"
                          @finish='remaining=false'
                          :time="60000"
                          format="ss 秒" />
          <van-button class='codeBtn'
                      v-else
                      size="small"
                      @click="onCode"
                      type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button class="logBtn"
                    block
                    :disabled='disabled'
                    type="info"
                    native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div class="footer">隐私条款</div>
  </div>
</template>

<script>
import { sendCode, login } from '@/utils/api.js'
export default {
  data () {
    return {
      mobile: '',
      code: '',
      remaining: false,
      disabled: true
    };
  },
  methods: {
    async onCode () {
      try {
        await sendCode(this.mobile)
        this.remaining = true
      } catch (error) {
        // 处理错误情况（状态码不是以 2 开头）
        if (error.response.status == 429) {
          this.$toast.fail('访问太频繁')
        } else {
          this.$toast.fail('失败，请重试')
        }
      }
    },
    async onSubmit () {
      try {
        let res = await login(this.mobile, this.code)

        // 把令牌保存到 vuex 中
        this.$store.commit('setUser', res.data.data)

        // 跳转到首页
        this.$router.push('/')

      } catch (error) {
        this.$toast.fail('登录失败，请重试！')
      }
    },
  },
};
</script>

<style lang="less">
.login {
  .loginName {
    width: calc(750px / 2);
    height: calc(128px / 2);
    font-family: MicrosoftYaHei;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0.5px;
    color: #ffffff;
    background-color: #3296fa;
    text-align: center;
    line-height: calc(128px / 2);
  }
  .logBtn {
    width: calc(694px / 2);
    height: 44px;
    font-size: 15px;
    border-radius: 5px;
  }
  .codeBtn {
    background-color: #ededed;
    color: #666666;
    border-radius: 11px;
  }
  .footer {
    font-size: calc(25px / 2);
    font-family: MicrosoftYaHei;
    font-weight: normal;
    font-stretch: normal;
    // line-height: 36px;
    text-align: center;
    letter-spacing: 1px;
    color: #666666;
    position: relative;
    bottom: 0;
  }
}
</style>